<script setup>
import { ref, computed, onMounted } from 'vue'
import { useContainerStore } from '../stores/containerStore'
import { useInsightStore } from '../stores/insightStore'

const containerStore = useContainerStore()
const insightStore = useInsightStore()

// 获取所有已完成的容器
const completedContainers = computed(() => containerStore.completedContainers)

// 获取统计数据
const averageEffectivenessScore = computed(() => insightStore.averageEffectivenessScore)
const timeEstimationAccuracy = computed(() => insightStore.timeEstimationAccuracy)
const effectiveBehaviorInsights = computed(() => insightStore.effectiveBehaviorInsights)

// 标签统计
const tagStatistics = computed(() => insightStore.tagStatistics)

// 图表数据
const effectivenessChartData = ref({
  labels: [],
  datasets: [
    {
      label: '有效性评分',
      backgroundColor: '#409EFF',
      data: []
    }
  ]
})

// 图表选项
const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    y: {
      beginAtZero: true,
      max: 5,
      ticks: {
        stepSize: 1
      }
    }
  }
}

// 初始化图表数据
function initChartData() {
  if (completedContainers.value.length === 0) return
  
  // 最多显示最近10条记录
  const recentContainers = [...completedContainers.value]
    .sort((a, b) => new Date(b.endTime) - new Date(a.endTime))
    .slice(0, 10)
    .reverse()
  
  effectivenessChartData.value.labels = recentContainers.map(c => c.title)
  effectivenessChartData.value.datasets[0].data = recentContainers.map(c => c.evaluation?.effectivenessScore || 0)
}

// 获取标签列表
function getTagList(type) {
  const stats = tagStatistics.value[type]
  return Object.entries(stats)
    .map(([tag, data]) => ({
      tag,
      ...data
    }))
    .sort((a, b) => b.count - a.count || b.avgScore - a.avgScore)
}

// 正向标签列表
const positiveTagList = computed(() => getTagList('positive'))

// 负向标签列表
const negativeTagList = computed(() => getTagList('negative'))

// 组件挂载时初始化图表数据
onMounted(() => {
  initChartData()
})
</script>

<template>
  <div class="insights-view">
    <h1>有效性洞察</h1>
    
    <div v-if="completedContainers.length === 0" class="no-data">
      <el-empty description="暂无数据，请先完成一些时间容器并进行评估" />
    </div>
    
    <template v-else>
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-card class="stat-card">
          <div class="stat-value">{{ averageEffectivenessScore }}</div>
          <div class="stat-label">平均有效性评分</div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-value">{{ timeEstimationAccuracy }}%</div>
          <div class="stat-label">时间预估准确率</div>
        </el-card>
        
        <el-card class="stat-card">
          <div class="stat-value">{{ completedContainers.length }}</div>
          <div class="stat-label">已完成容器数</div>
        </el-card>
      </div>
      
      <!-- 有效性趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <h2>有效性评分趋势</h2>
        </template>
        
        <div class="chart-container">
          <canvas id="effectiveness-chart"></canvas>
        </div>
      </el-card>
      
      <!-- 行为洞察 -->
      <el-card class="insights-card">
        <template #header>
          <h2>行为有效性洞察</h2>
        </template>
        
        <div v-if="effectiveBehaviorInsights.length === 0" class="no-insights">
          <p>暂无足够数据生成洞察，请继续记录更多时间容器</p>
        </div>
        
        <div v-else class="insights-list">
          <div 
            v-for="(insight, index) in effectiveBehaviorInsights" 
            :key="index"
            class="insight-item"
            :class="{ 'positive': insight.type === 'positive', 'negative': insight.type === 'negative' }"
          >
            <el-icon v-if="insight.type === 'positive'"><Star /></el-icon>
            <el-icon v-else><Warning /></el-icon>
            <span>{{ insight.message }}</span>
          </div>
        </div>
      </el-card>
      
      <!-- 标签分析 -->
      <div class="tags-analysis">
        <!-- 正向标签 -->
        <el-card class="tag-card">
          <template #header>
            <h2>正向标签分析</h2>
          </template>
          
          <div class="tag-list">
            <div v-for="tag in positiveTagList" :key="tag.tag" class="tag-item">
              <div class="tag-name">{{ tag.tag }}</div>
              <div class="tag-stats">
                <div class="tag-count">{{ tag.count }}次</div>
                <div class="tag-score">{{ tag.avgScore }}星</div>
              </div>
              <el-progress 
                :percentage="tag.avgScore * 20" 
                :color="'#67C23A'" 
                :show-text="false" 
              />
            </div>
          </div>
        </el-card>
        
        <!-- 负向标签 -->
        <el-card class="tag-card">
          <template #header>
            <h2>负向标签分析</h2>
          </template>
          
          <div class="tag-list">
            <div v-for="tag in negativeTagList" :key="tag.tag" class="tag-item">
              <div class="tag-name">{{ tag.tag }}</div>
              <div class="tag-stats">
                <div class="tag-count">{{ tag.count }}次</div>
                <div class="tag-score">{{ tag.avgScore }}星</div>
              </div>
              <el-progress 
                :percentage="tag.avgScore * 20" 
                :color="'#F56C6C'" 
                :show-text="false" 
              />
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 容器历史记录 -->
      <el-card class="history-card">
        <template #header>
          <h2>容器历史记录</h2>
        </template>
        
        <el-table :data="completedContainers" style="width: 100%">
          <el-table-column prop="title" label="容器名称" />
          <el-table-column prop="category" label="分类" width="100">
            <template #default="scope">
              <el-tag>{{ scope.row.category }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="evaluation.effectivenessScore" label="有效性评分" width="100">
            <template #default="scope">
              <el-rate 
                v-model="scope.row.evaluation.effectivenessScore" 
                disabled 
                :colors="['#F56C6C', '#E6A23C', '#67C23A']"
                :max="5"
              />
            </template>
          </el-table-column>
          <el-table-column label="时间对比" width="180">
            <template #default="scope">
              <div>预估: {{ scope.row.estimatedTime }}分钟</div>
              <div>实际: {{ scope.row.actualTime }}分钟</div>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="完成时间" width="180" />
        </el-table>
      </el-card>
    </template>
  </div>
</template>

<style scoped>
.insights-view {
  max-width: 1000px;
  margin: 0 auto;
}

.insights-view h1 {
  margin-bottom: 30px;
  text-align: center;
  color: #303133;
}

.no-data {
  margin: 50px 0;
  text-align: center;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 2.5rem;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.stat-label {
  color: #606266;
  font-size: 1rem;
}

.chart-card {
  margin-bottom: 30px;
}

.chart-card h2 {
  margin: 0;
  font-size: 1.2rem;
}

.chart-container {
  height: 300px;
  position: relative;
}

.insights-card {
  margin-bottom: 30px;
}

.insights-card h2 {
  margin: 0;
  font-size: 1.2rem;
}

.no-insights {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.insights-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.insight-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 4px;
  gap: 10px;
}

.insight-item.positive {
  background-color: rgba(103, 194, 58, 0.1);
  border-left: 4px solid #67C23A;
}

.insight-item.negative {
  background-color: rgba(245, 108, 108, 0.1);
  border-left: 4px solid #F56C6C;
}

.tags-analysis {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.tag-card h2 {
  margin: 0;
  font-size: 1.2rem;
}

.tag-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.tag-item {
  margin-bottom: 10px;
}

.tag-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.tag-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.9rem;
  color: #606266;
}

.history-card {
  margin-bottom: 30px;
}

.history-card h2 {
  margin: 0;
  font-size: 1.2rem;
}
</style>